<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 职工代表大会编辑 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel != 0 ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="年度计划"></title-name>
          <custom-form :isEmit="false" :formList="formList" :form="form" :editModel="editModel == 0 ? '' : ''" @selectOrg="selectOrg" @getProjectInfo="getProjectInfo"> </custom-form>
        </a-card>
        <a-card :bordered="false">
          <title-name title="技术复核年度计划表"></title-name>
          <a-button class="mb12" type="primary" icon="plus" v-if="editModel != 0" @click="addLine()" :disabled="!form.projectId || !form.year">新增行</a-button>
          <!-- 导出 -->
          <excel class="ml12 mb12" ref="exportAll" :fileName="projectName" is-click-generate="false">
            <a-button type="primary" icon="download" slot="excelBtn" :disabled="form.technicalReviewYearlyPlans && form.technicalReviewYearlyPlans.length == 0" @click="exportAll">导出数据</a-button>
          </excel>
          <!-- 表格 -->
          <s-table
            bordered
            ref="table"
            tableLayout="fixed"
            size="default"
            rowKey="id"
            :columns="editModel != '0' ? columns : columnsLook"
            :data="loadData"
            :alert="true"
            show-size-changer
            show-quick-jumper
            :showPagination="false"
            :scrollX="1200"
          >
            <template v-for="col in ['checkProjectId', 'checkContentId', 'organizerId', 'chargePersonIds', 'plannedCompletionTime']" :slot="col" slot-scope="text, record">
              <div :key="col" class="form-item">
                <template>
                  <a-select v-if="col === 'checkProjectId'" v-model="record.checkProjectId" show-search :filter-option="filterOption" :disabled="editModel == 0" @change="checkProjectChange(record)">
                    <a-select-option v-for="item in checkProjectArr" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                  <a-select v-else-if="col === 'checkContentId'" v-model="record.checkContentId" show-search :filter-option="filterOption" :disabled="editModel == 0" @change="checkContentChange(record)">
                    <a-select-option v-for="item in record.checkContentArr" :key="item.id" :value="item.id">
                      {{ item.content }}
                    </a-select-option>
                  </a-select>
                  <!-- <div v-else-if="col === 'checkContentId'">
                    <BaseInput v-if="record.compoundContent" class="compoundContentStatus" disabled v-model="record.compoundContent"> </BaseInput>
                    <a-select
                      v-else
                      show-search
                      :filter-option="filterOption"
                      :disabled="editModel == 0 || form.auditStatus == 3 || form.auditStatus == 1"
                      v-model="record.checkContentId"
                      @change="checkContentChange(record)"
                    >
                      <a-select-option v-for="item in record.checkContentArr" :key="item.id" :value="item.id">
                        {{ item.content }}
                      </a-select-option>
                    </a-select>
                  </div> -->
                  <SelectPersonByProject
                    v-else-if="col === 'organizerId'"
                    v-model="record.organizerId"
                    :disabled="editModel == 0"
                    placeholder="请选择"
                    :isOrg="true"
                    :orgId="form.projectDeptId"
                    :addPhone="true"
                    :isEdit="editModel != '2'"
                    :show-search="true"
                    @personChanged="personChanged($event, record)"
                  />
                  <SelectPersonByProject
                    v-else-if="col === 'chargePersonIds'"
                    v-model="record.chargePersonIds"
                    :disabled="editModel == 0"
                    placeholder="请选择"
                    mode="multiple"
                    :isOrg="true"
                    :orgId="form.projectDeptId"
                    :addPhone="true"
                    :isEdit="editModel != '2'"
                    :show-search="true"
                    @personChanged="personChangeds($event, record)"
                  />
                  <a-date-picker
                    v-else-if="col === 'plannedCompletionTime'"
                    v-model="record.plannedCompletionTime"
                    :disabled="editModel == 0"
                    :disabledDate="disabledYears"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD"
                  />
                  <BaseInput v-else :disabled="editModel == 0" v-model="record[col]"> </BaseInput>

                  <!-- <template v-else> {{ col === 'name' ? '' : text }}</template> -->
                </template>
              </div></template
            >
            <template slot="operation" slot-scope="text, record, index">
              <span v-if="!record.compoundContent">
                <a-popconfirm title="确定要删除?" @confirm="() => del(record, index)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
            </template>
            <!-- <template v-if="editModel != 0" slot="footer"> <a @click="addLine">添加行</a> </template> -->
          </s-table>
        </a-card>

        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" v-if="editModel != 0">
          <a-button class="button_right" v-if="form.status == 'REJECTED'" type="primary" :loading="loadingBtn.REJECTED" @click="handleSubmit('REJECTED')">保存</a-button>
          <a-button v-else class="button_right" type="primary" :loading="loadingBtn.DRAFT" @click="handleSubmit('DRAFT')">保存草稿</a-button>
          <a-button class="button_right" type="primary" :loading="loadingBtn.SUBMITTED" @click="handleSubmit('SUBMITTED')">提交</a-button>
          <a-button type="primary" @click="handleActiveClose">关闭</a-button>
        </div>
        <div class="btn_box page-btn-right-top" v-else-if="!isConsultation">
          <a-button type="primary" @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
    <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { getTechnicalYearlyPlanById, addTechnicalYearlyPlan, updateTechnicalYearlyPlan } from '@/api/technical/technicalReview'
import { getReviewCheckProjectAll, getReviewContentAll } from '@/api/technical/reviewContent'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import Selector from '@/components/Select/Selector'
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '复核项目',
    dataIndex: 'checkProjectId',
    scopedSlots: { customRender: 'checkProjectId' }
  },
  {
    title: '复核内容',
    dataIndex: 'checkContentId',
    scopedSlots: { customRender: 'checkContentId' }
  },
  {
    title: '组织人',
    dataIndex: 'organizerId',
    scopedSlots: { customRender: 'organizerId' }
  },
  {
    title: '责任人',
    dataIndex: 'chargePersonIds',
    scopedSlots: { customRender: 'chargePersonIds' }
  },
  {
    title: '计划完成时间',
    dataIndex: 'plannedCompletionTime',
    scopedSlots: { customRender: 'plannedCompletionTime' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '230px',
    scopedSlots: { customRender: 'operation' }
  }
]
const columnsLook = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '复核项目',
    dataIndex: 'checkProjectId',
    scopedSlots: { customRender: 'checkProjectId' }
  },
  {
    title: '复核内容',
    dataIndex: 'checkContentId',
    scopedSlots: { customRender: 'checkContentId' }
  },
  {
    title: '组织人',
    dataIndex: 'organizerId',
    scopedSlots: { customRender: 'organizerId' }
  },
  {
    title: '责任人',
    dataIndex: 'chargePersonIds',
    scopedSlots: { customRender: 'chargePersonIds' }
  },
  {
    title: '计划完成时间',
    dataIndex: 'plannedCompletionTime',
    scopedSlots: { customRender: 'plannedCompletionTime' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectPersonModal,
    SelectPersonByProject
  },
  data() {
    this.columns = columns
    this.columnsLook = columnsLook
    return {
      checkProjectArr: [], //复核项目数组
      loading: false, // 加载控件
      visible: false, //弹窗控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: { technicalReviewYearlyPlans: [], projectDeptId: '', curId: '', projectId: '', branchComId: '' }, // 表单
      id: '',
      yearsOpen: false,
      projectName: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      copyForm: {},
      dialogForm: {},
      rules: {
        year: [{ required: true, message: '请选择' }],
        projectLocation: [{ required: true, message: '请输入' }],
        projectOverview: [{ required: true, message: '请输入' }]
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.technicalReviewYearlyPlans || []
          })
        })
      },

      init: false, // 初始化控件
      titles: ['年度计划查看', '年度计划编辑', '年度计划新增'],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    $route(to, from) {
      this.yearsOpen = false
    },
    // 监听附件实现附件校验
    'form.year'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('year')
        })
      }
    },
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
  async mounted() {
    this.$refs.exportAll?.tableToExcelFile(
      {
        columns: [
          { title: '复核项目', dataIndex: 'checkProjectName' },
          { title: '复核内容', dataIndex: 'checkContentName' },
          { title: '组织人', dataIndex: 'organizerName' },
          { title: '责任人', dataIndex: 'chargePersonNames' },
          { title: '计划完成时间', dataIndex: 'plannedCompletionTime' }
        ]
      },
      0
    )
    this.$route.meta.title = ['年度计划查看', '年度计划编辑', '年度计划新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.getDetails()
    } else {
      this.form.curId = this.$userInfo().currentPost.id
      this.$nextTick(() => {
        this.init = true
      })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('technical_yearly_plan_audit')
    this.getReviewContent()
  },
  computed: {
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          checkStrictly: true,
          isAutoSelectFirst: true,
          span: 16,
          disabled: this.editModel == 0,
          isNeedAuth: true,
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }]
        },
        // {
        //   label: '所属单位',
        //   type: 'orgTree',
        //   keyName: 'curId',
        //   rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
        //   span: 16,
        //   isAutoSelectFirst: true,
        //   isNeedAuth: true,
        //   checkStrictly: true,
        //   disabled: true,
        //   statusSet: [1, 2, 3, 4, 5, 6],
        //   isQueryProjecDetail: true
        // },
        // {
        //   type: SelectSubCompany,
        //
        //   keyName: 'branchComId',
        //   label: '分公司名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '项目名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchComId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   },
        //   selectChange: (e) => {
        //     console.log(e)
        //     this.form.projectDeptId = e?.projectDeptId
        //     this.projectName = e?.name
        //   }
        // },
        {
          keyName: 'year',
          type: 'a-date-picker',
          label: '年份',
          disabled: this.editModel == 0,
          attrs: {
            mode: 'year',
            format: 'YYYY',
            valueFormat: 'YYYY',
            open: this.yearsOpen
          },
          openChange: () => {
            this.yearsOpen = true
          },
          panelChange: () => {
            this.yearsOpen = false
          },
          change: () => {
            this.yearsOpen = false
          }
        },
        {
          keyName: 'projectLocation',
          type: 'BaseTextarea',
          label: '项目地点',
          disabled: this.editModel == 0,
          span: 24
        },
        {
          keyName: 'projectOverview',
          type: 'BaseTextarea',
          label: '项目概况',
          disabled: this.editModel == 0,
          span: 24
        }
      ]
    }
  },
  methods: {
    /**
     * @description: 过滤数据
     * @param
     * @return {res.data}
     */
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /**
     * @description: 获取复核项目
     * @param status  状态
     * @return {res.data}
     */
    async getReviewContent() {
      let params = { status: true }
      let res = await getReviewCheckProjectAll(params)
      if (res.data) {
        this.checkProjectArr = res.data
      }
    },
    /**
     * @description:                 获取内容
     * @param record.checkProjectId  复核项目id
     * @return                       {res.data}
     */

    async checkProjectChange(record) {
      this.$set(record, 'checkContentId', '')
      this.$set(record, 'checkContentName', '');
      if(record.compoundContent){
        this.$set(record, 'compoundContent', '');
      }
      console.log('record',record)
      this.checkProjectArr.forEach((item) => {
        if (item.id === record.checkProjectId) {
          this.$nextTick(() => {
            record.checkProjectName = item.name
          })
        }
      })
      let params = { checkId: record.checkProjectId, status: true }
      let res = await getReviewContentAll(params)
      if (res.data) {
        this.$set(record, 'checkContentArr', res.data)
      }
    },
    //更新内容
    checkContentChange(record) {
      if (!record.checkProjectId) {
        this.$message.warning('复核项目不能为空')
        return
      }
      record.checkContentArr.forEach((item) => {
        if (item.id === record.checkContentId) {
          record.checkContentName = item.content
        }
      })
    },
    selectOrg(val) {
      if (val.length && val.length < 2) {
        this.form.branchComId = val[val.length - 1].orgId
      } else if (val.length >= 2) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.projectName = val[val.length - 1].projectName
        this.form.projectId = val[val.length - 1].projectId
      }
    },
    getProjectInfo(info) {
      this.$set(this.form, 'projectDeptId', info.projectDeptOrgId)
    },
    //时间选择限制
    disabledYears(current) {
      return (current && current < this.moment(this.form.year).startOf('year')) || current > this.moment(this.form.year).endOf('year')
    },
    //添加表格行
    addLine() {
      this.form.technicalReviewYearlyPlans.push({
        checkProjectId: undefined,
        checkContentId: undefined,
        organizerId: undefined,
        chargePersonIds: [],
        plannedCompletionTime: undefined
      })
      this.getReviewContent()
      this.$refs.table.refresh(true)
    },
    // 删除
    del(data, idx) {
      this.form.technicalReviewYearlyPlans.splice(idx, 1)
      this.$refs.table.refresh(true)
    },
    //导出
    exportAll() {
      this.$refs.exportAll.setDataAndGenerate(this.form.technicalReviewYearlyPlans)
    },
    //
    personChangeds(e, record) {
      record.chargePersonNames = ''
      e instanceof Array &&
        e?.forEach((i) => {
          record.chargePersonNames += i.employeeName + ' '
        })
    },
    personChanged(e, record) {
      record.organizerName = e.employeeName
    },
    getDetails() {
      this.loading = true
      getTechnicalYearlyPlanById({ id: this.id })
        .then((res) => {
          this.loading = false
          this.form = res.data
          if (this.form.projectId) {
            this.form.curId = this.form.projectId
          } else {
            this.form.curId = this.form.branchComId
          }
          this.form.technicalReviewYearlyPlans.forEach((item) => {
            if (item.compoundContent) {//历史数据
              let arr = []
              item.checkContentName = item.compoundContent
              item.checkContentId = '123456789'
              arr.push({
                content: item.compoundContent,
                id: '123456789'
              })
              this.$set(item, 'checkContentArr', arr)
              return false
            }
            if (item.checkProjectId) {//
              let params = { checkId: item.checkProjectId, status: true }
              getReviewContentAll(params)
                .then((res) => {
                  this.$set(item, 'checkContentArr', res.data)
                })
                .catch((error) => {
                  console.log(error)
                })
            }
          })
          this.$refs.table.loadData()
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    /**
     * 提交表单
     */
    validateForm() {
      let flag1 = true
      let flag2 = true
      this.$refs.ruleForm.validate((e) => {
        flag1 = e
      })
      if (this.form.technicalReviewYearlyPlans.length > 0) {
        this.form.technicalReviewYearlyPlans.forEach((i) => {
          if (!i.checkProjectId || !i.checkContentId || !i.organizerId || i.chargePersonIds.length == 0 || !i.plannedCompletionTime) {
            flag2 = false
          }
        })
        if (!flag2) {
          this.$message.warning('请填写完整计划表数据')
        }
      } else {
        this.$message.warning('请添加计划表数据')
        flag2 = false
      }
      if (flag1 && flag2) {
        return true
      } else {
        return false
      }
    },
    okSubmit(status) {
      this.loading = true
      this.loadingBtn[status] = true

      let form = this.$clone(this.form)
      if (status != 'REJECTED') {
        form.auditStatus = status == 'SUBMITTED' ? 1 : 0
      } else {
        form.auditStatus = 5
      }
      if (typeof form.year !== 'string') {
        form.year = this.$dateFormat(form.year, 'Y')
      }

      let api = [updateTechnicalYearlyPlan, addTechnicalYearlyPlan][this.editModel - 1] // 根据操作切换url地址
      this.submitApprovalConfirm(status == 'SUBMITTED' ? this.processConfig : 6, (flag) => {
        if (!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
        api(form)
          .then((res) => {
            this.loading = false
            this.loadingBtn[status] = false
            this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
            if (status == 'SUBMITTED') {
              //提交时，返回id
              this.businessId = res.data.id
              this.setProcessConfig = this.processConfig
              return
            } else {
              this.$multiTab.close()
            }
          })
          .catch(() => {
            this.loadingBtn[status] = false
            this.loading = false
            this.$message.warning(err.data.message)
          })
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      this.setProcessConfig = null
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return false
      }
      if (status == 'SUBMITTED') {
        // this.$confirm({
        //   title: '温馨提示',
        //   content: '提交后不可修改，确认填写完成并提交吗？',
        //   onOk: () => {
        //     return
        this.okSubmit(status)
        // }
        // })
      } else {
        this.okSubmit(status)
      }
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
/deep/.inpWidth {
  border-color: #e4ac0b;
  background-color: #fff9e8;
}
/deep/.inpWidth[disabled] {
  border-color: #d9d9d9 !important;
  background-color: #f5f5f5 !important;
}
</style>
